package recover_func

import (
	sysContext "context"
	"encoding/json"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/context"
	"go-beego-api/component/ck_log"
	"go.uber.org/zap"
	"runtime/debug"
)

// RecoverPanicCtx goroutine处理panic
func RecoverPanicCtx(ctx sysContext.Context) {
	if err := recover(); err != nil {
		ck_log.LogCtx(ctx).Errorw("RecoverPanic", zap.String("stack", string(debug.Stack())), zap.Any("error", err))

		//ck_log.LogCtx(ctx).With(zap.AddCallerSkip(1)).Errorw(fmt.Sprintf("RecoverPanic:%v", err))
	}
}

// RequestRecoverPanic 请求panic
func RequestRecoverPanic(ctx *context.Context) {
	if err := recover(); err != nil {
		if err == beego.ErrAbort {
			return
		}
		if !beego.BConfig.RecoverPanic {
			panic(err)
		}
		sysCtxI := ctx.Input.GetData("ReqContext")
		sysCtx := sysContext.Background()
		if sysCtxI != nil {
			sysCtx = sysCtxI.(sysContext.Context)
		}
		ck_log.LogCtx(sysCtx).Errorw("RequestRecoverPanic", zap.String("stack", string(debug.Stack())), zap.Any("error", err))
		//ck_log.LogCtx(sysCtx).With(zap.AddCallerSkip(1)).Errorw(fmt.Sprintf("RequestRecoverPanic:%v", err))
		if ctx.Output.Status != 0 {
			ctx.ResponseWriter.WriteHeader(ctx.Output.Status)
		} else {
			ctx.ResponseWriter.WriteHeader(200)
		}
		response := map[string]interface{}{
			"code":    50000,
			"message": "[CRITICAL] 服务器开小差了，过会儿重试",
		}
		jb, _ := json.Marshal(response)
		ctx.ResponseWriter.Header().Set("Content-Type", "application/json; charset=utf-8")
		_, _ = ctx.ResponseWriter.Write(jb)
	}
}
